package com.success.application.shop.activity;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Dialog;
import android.content.ContentUris;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.reflect.TypeToken;
import com.success.application.api.YuanbaoApi;
import com.success.application.base.BaseDetailActivity;
import com.success.application.common.param.Params;
import com.success.application.common.result.Result;
import com.success.application.myapplication.R;
import com.success.application.user.AccountHelper;
import com.success.application.user.activity.UserMessageActivity;
import com.success.application.util.DatePickerDialog;
import com.success.application.util.DialogHelper;
import com.success.application.widget.SimplexToast;
import com.success.application.widget.popup.InputPopup;
import com.success.application.widget.popup.ListPopup;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.Calendar;
import java.util.Map;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * Created by mzk on 2017/2/9.
 */

public class WishPubActivity extends BaseDetailActivity<Map> {

    @Bind(R.id.tv_wish_title)
    TextView tv_wish_title;//主题

    @Bind(R.id.edit_content)
    EditText ed_constent;//描述==详情
    @Bind(R.id.tv_wish_img)
    ImageView tv_wish_img;//上传的图片
    //上传来的图片
    @Bind(R.id.iv_wish_pt)
    ImageView iv_wish_pt;
    @Bind(R.id.tv_popup_show)
    TextView tv_popupShow;//许愿类别
    @Bind(R.id.tv_csrq)
    TextView mCsrq;//出生日期的值
    private String xylb = "";//许愿类别
    private Dialog mDialog;
    public static final int REQUEST_PERMISSION_READ_EXTERNAL_STORAGE = 1;
    public static final int REQUEST_PERMISSION_WRITE_EXTERNAL_STORAGE = 4;
    public static final int REQUEST_PERMISSION_CAMERA = 3;
    private static final int CHOOSE_PHOTO = 5;
    private static final int TAKE_PHOTO = 6;
    private String txlj;//头像路径
    private Uri imageUri;
    @Override
    protected Type getType() {
        return new TypeToken<Result<Map>>() {
        }.getType();
    }

    @Override
    protected void setData(Result<Map> result) {
        if (mDialog != null) {
            mDialog.dismiss();
        }
        if(Result.RESULT_SUCCESS.equals(result.getResult())){
           SimplexToast.show(getApplicationContext(), "发布成功");
            //新增回调刷新列表
            setResult(1);
            finish();
        }
    }

    @Override
    protected int getContentLayoutId() {
        return R.layout.shop_wish_activity_publish;
    }

    @Override
    protected int getTitleRes() {
        return R.string.shop_help_publish;
    }

    protected int getLeftIconRes() {
        return R.drawable.selector_nav_back_light;
    }

    @Override
    protected int getRightIconRes() {
        return R.mipmap.save;
    }

    @Override
    protected View.OnClickListener getLeftIconClickListener() {
        return new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setResult(1);
                finish();
            }
        };
    }


    @Override
    protected boolean initBundle(Bundle bundle) {
        return super.initBundle(bundle);
    }

    @Override
    protected void initWidget() {
        super.initWidget();
    }

    @Override
    protected void initData() {
        super.initData();
    }
    @OnClick(R.id.tv_wish_title)
    void onClickTitle() {
        InputPopup inputPopup = new InputPopup(this, tv_wish_title, "求助主题", tv_wish_title.getText().toString());
        inputPopup.showPopupWindow();
    }
//    @OnClick(R.id.tv_help_phone)
//    void onClickPhone() {
//        InputPopup inputPopup = new InputPopup(this, tv_help_phone, "联系电话", tv_help_phone.getText().toString());
//        inputPopup.showPopupWindow();
//    }
    @OnClick(R.id.tv_popup_show)
    void selectZXLB(){
        ListPopup.Builder builder=new ListPopup.Builder(this);
        builder.addItem("1","许愿");
        builder.addItem("2","表白");
        builder.build(new ListPopup.OnListPopupItemClickListener() {
            @Override
            public void onItemClick(String label, String value) {
                tv_popupShow.setText(label);
                xylb = value;
            }
        }).showPopupWindow();

    }
    //点击日期控件
    @OnClick(R.id.ll_message_csrq)
    void OnClickDatePicker() {
        mCsrq = (TextView) findViewById(R.id.tv_csrq);
        Calendar c = Calendar.getInstance();
        new DatePickerDialog(WishPubActivity.this, 0, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker startDatePicker, int startYear, int startMonthOfYear,
                                  int startDayOfMonth) {
                String textString = String.format("%d-%d-%d", startYear,
                        startMonthOfYear + 1, startDayOfMonth);
                mCsrq.setText(textString);
            }
        }, c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DATE), true).show();
    }
    //点击图片
    @OnClick(R.id.tv_wish_img)
    void helpImg(){
        ListPopup.Builder builder = new ListPopup.Builder(this);
        builder.addItem("1", "拍照");
        builder.addItem("2", "从相册选取");
        builder.build(new ListPopup.OnListPopupItemClickListener() {
            @Override
            public void onItemClick(String label, String value) {
                if(value=="1"){
                    takePhoto();
                }else{
                    if (ContextCompat.checkSelfPermission(WishPubActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                        ActivityCompat.requestPermissions(WishPubActivity.this, new String[]{
                                Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_PERMISSION_READ_EXTERNAL_STORAGE);
                    }else if (ContextCompat.checkSelfPermission(WishPubActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                        ActivityCompat.requestPermissions(WishPubActivity.this, new String[]{
                                Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_PERMISSION_WRITE_EXTERNAL_STORAGE);
                    }else if (ContextCompat.checkSelfPermission(WishPubActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                        ActivityCompat.requestPermissions(WishPubActivity.this, new String[]{
                                Manifest.permission.CAMERA}, REQUEST_PERMISSION_CAMERA);
                    } else {
                        openAlbum();
                    }
                }
//                tv_popupShow.setText(label);
//                mxbvalue.setText(value);
            }
        }).showPopupWindow();
          /*
        if 没有相机权限，
            去请求权限requestPermissions（1） --> onRequestPermissionsResult(1)
        else
            直接打开
         */
    }
    //拍照
    private void takePhoto(){
        File outputImage = new File(getExternalCacheDir(),"output_image.jpg");
        try{
            if(outputImage.exists()){
                outputImage.delete();
            }
            outputImage.createNewFile();
        }catch (IOException e){
            e.printStackTrace();
        }
        if(Build.VERSION.SDK_INT>=24){
            imageUri = FileProvider.getUriForFile(WishPubActivity.this,"com.example.cameraalbumtest.fileprovider",outputImage);

        }else{
            imageUri = Uri.fromFile(outputImage);
        }
        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
        intent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri);
        startActivityForResult(intent,TAKE_PHOTO);
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case REQUEST_PERMISSION_READ_EXTERNAL_STORAGE:
                //提示没有读文件权限，并打开系统设置界面
                if (grantResults.length > 0 && grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                    showSETTINGS("读文件");
                }
                break;
            case REQUEST_PERMISSION_WRITE_EXTERNAL_STORAGE:
                //提示没有写文件权限，并打开系统设置界面
                if (grantResults.length > 0 && grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                    showSETTINGS("写文件");
                }
                break;
            case REQUEST_PERMISSION_CAMERA:
                //提示没有相机权限，并打开系统设置界面
                if (grantResults.length > 0 && grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                    showSETTINGS("相机");
                } else {
                    openAlbum();
                }
                break;
            default:
        }
    }

    private void showSETTINGS(String permissStr) {
        DialogHelper.getConfirmDialog(this, "", "没有" + permissStr + "权限, 你需要去设置中开启.", "去设置", "取消", false, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                startActivity(new Intent(Settings.ACTION_APPLICATION_SETTINGS));
            }
        }, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
            }
        }).show();
    }

    private void openAlbum() {
        Intent intent = new Intent("android.intent.action.GET_CONTENT");
        intent.setType("image/*");
        startActivityForResult(intent, CHOOSE_PHOTO);//打开相册
    }

    @TargetApi(19)
    private void handleImageOnKitKat(Intent data) {
        String imagePath = null;
        Uri uri = data.getData();
        if (DocumentsContract.isDocumentUri(this, uri)) {
            String docId = DocumentsContract.getDocumentId(uri);
            if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
                String id = docId.split(":")[1];
                String selection = MediaStore.Images.Media._ID + "=" + id;
                imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
            } else if ("con.android.providers.downloads.documents".equals(uri.getAuthority())) {
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public/public_downloads"), Long.valueOf(docId));
                imagePath = getImagePath(contentUri, null);
            }
        } else if ("content".equalsIgnoreCase(uri.getScheme())) {
            imagePath = getImagePath(uri, null);
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            imagePath = uri.getPath();
        }
        displayImage(imagePath);
    }

    private void handleImageBeforeKitKat(Intent data) {
        Uri uri = data.getData();
        String imagePath = getImagePath(uri, null);
        displayImage(imagePath);
    }

    private String getImagePath(Uri uri, String selection) {
        String path = null;
        Cursor cursor = getContentResolver().query(uri, null, selection, null, null);
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }

    private void displayImage(String imagePath) {
        if (imagePath != null) {
            Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
            txlj = imagePath;
            tv_wish_img.setImageBitmap(bitmap);
            iv_wish_pt.setImageBitmap(bitmap);
//            if (Build.VERSION.SDK_INT >= 19) {
//                Intent intent = new Intent();
//                intent.setClass(getApplicationContext(), CropActivity.class);
//                intent.putExtra("txlj", imagePath);
//                startActivityForResult(intent, 0x04);
//            } else {
//                Intent intent = new Intent();
//                intent.setClass(getApplicationContext(), CropActivity.class);
//                intent.putExtra("txlj", imagePath);
//                startActivityForResult(intent, 0x04);
//            }
        } else {
            Toast.makeText(this, "获取图片失败", Toast.LENGTH_SHORT).show();
        }
    }
    @Override
    protected View.OnClickListener getRightIconClickListener() {
        return new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(TextUtils.isEmpty(tv_wish_title.getText())){
                    SimplexToast.show(WishPubActivity.this, "您还没有填写许愿主题", Toast.LENGTH_SHORT);
                    return;
                }
                if(TextUtils.isEmpty(tv_popupShow.getText())){
                    SimplexToast.show(WishPubActivity.this,"您还没有填写许愿类型",Toast.LENGTH_SHORT);
                    return;
                }
                if(TextUtils.isEmpty(mCsrq.getText())){
                    SimplexToast.show(WishPubActivity.this,"您还没有填写截止时间",Toast.LENGTH_SHORT);
                    return;
                }
                if(TextUtils.isEmpty(ed_constent.getText())){
                    SimplexToast.show(WishPubActivity.this,"您还没有填写许愿描述",Toast.LENGTH_SHORT);
                    return;
                }
                mDialog = DialogHelper.getProgressDialog(WishPubActivity.this, "提交中");
                mDialog.show();
                try{
                    Params params = new Params();
                    params.put("userId", AccountHelper.getUserId());
                    params.put("model.xyjy_ztc",tv_wish_title.getText());
                    params.put("model.xyjy_xylb",xylb);
                    params.put("model.xyjy_jzsj",mCsrq.getText());
                    params.put("model.xyjy_xq",ed_constent.getText());
                    YuanbaoApi.addXyjy(params,mHandler);
                }catch (Exception e){
                    SimplexToast.show(getApplicationContext(), "读取数据失败！");

                    e.printStackTrace();
                }

            }
        };
    }

    @OnClick(R.id.main_layout)
    void dismissKeyborade(View v){
        InputMethodManager imm = (InputMethodManager)
                getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
    }
}
